package net.lainiao.zhihu.backserver;

import net.lainiao.zhihu.dao.ZhihudaanMapper;
import net.lainiao.zhihu.dao.ZhihuhuatipagelinksMapper;
import net.lainiao.zhihu.dao.ZhihuwentiMapper;
import net.lainiao.zhihu.model.Zhihudaan;
import net.lainiao.zhihu.model.Zhihuhuatipagelinks;
import net.lainiao.zhihu.model.ZhihuwentiWithBLOBs;
import org.springframework.context.ApplicationContext;
import net.lainiao.zhihu.reptitle.ZhihuQuestion;

/**
 * Created by Administrator on 2016/1/16.
 */
public class ZhihuhuatiPageLinkTask extends ZhihuTask implements Runnable {
    public ZhihuhuatiPageLinkTask(ApplicationContext context) {
        super(context);
    }

    public void run() {
        ZhihuwentiMapper zhihuwentiMapper = context.getBean(ZhihuwentiMapper.class);
        ZhihudaanMapper zhihudaanMapper = context.getBean(ZhihudaanMapper.class);
        ZhihuhuatipagelinksMapper zhihuhuatipagelinksMapper = context.getBean(ZhihuhuatipagelinksMapper.class);
        Zhihuhuatipagelinks zhihuhuatipagelinks=null;
        while (status == 1) {
            zhihuhuatipagelinks = zhihuhuatipagelinksMapper.getNext();
            if(zhihuhuatipagelinks==null){
                System.out.println("没有有效数据");
                break;
            }
            String url = zhihuhuatipagelinks.getUrl();
            try {
                ZhihuwentiWithBLOBs zhihuwenti = ZhihuQuestion.parseQuestion(url);
                zhihuwenti.setZhlinkId(zhihuhuatipagelinks.getId());
                zhihuwentiMapper.insert(zhihuwenti);
                for (Zhihudaan zhihudaan : zhihuwenti.getZhihudaans()) {
                    zhihudaanMapper.insert(zhihudaan);
                    Thread.sleep(500);
                }
                zhihuhuatipagelinks.setStatus(1);
                zhihuhuatipagelinksMapper.updateByPrimaryKey(zhihuhuatipagelinks);
            } catch (Exception e) {
                e.printStackTrace();
                zhihuhuatipagelinks.setStatus(2);
                zhihuhuatipagelinksMapper.updateByPrimaryKey(zhihuhuatipagelinks);
            }
        }
    }
}
